package com.blazhovsky.mk.androidlan;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.AsyncTask;
import android.widget.ArrayAdapter;

public class NitkaZaPrimanje
{
	MainActivity context;
	
	DataInputStream dataInputStreamZaPrimanje = null;
	Socket socketZaPrimanje = null;
	String dobienaPoraka = "";
	
	public NitkaZaPrimanje(MainActivity c, Socket socket)
	{
		context = c;
		socketZaPrimanje = socket;
	}
	
	public void pocni()
	{
		new MyAsyncTaskPrimanje().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
	}
	
	public class MyAsyncTaskPrimanje extends AsyncTask<Void, Void, Void>
	{
		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params)
		{	
			try
			{
				String cela;
				cela = socketZaPrimanje.getInetAddress().toString();
				context.klientIP = cela.substring(1);
				if(!context.adresi.contains(context.klientIP))
					context.adresi.add(context.klientIP);
				
				dataInputStreamZaPrimanje = new DataInputStream(socketZaPrimanje.getInputStream());
				
				System.out.println("Probuvam da primam odgovor!");
				dobienaPoraka += "ip: " + context.klientIP + ": " + dataInputStreamZaPrimanje.readUTF() + "\n";
				System.out.println("ip: " + socketZaPrimanje.getInetAddress());
				System.out.println(dobienaPoraka);
			}
			catch (UnknownHostException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			finally
			{
				if (socketZaPrimanje != null)
				{
					try
					{
						socketZaPrimanje.close();
					}
					catch (IOException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if (dataInputStreamZaPrimanje != null)
				{
					try
					{
						dataInputStreamZaPrimanje.close();
					}
					catch (IOException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
			
			ArrayAdapter<String> arrayAdapter =      
			         new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1, context.adresi);
			context.adresiZaPrakjanje.setAdapter(arrayAdapter); 
			
			context.refresh(dobienaPoraka);
		}
	}
}
